using System;
using System.IO;
using System.Reflection;
using FireStarter.CodeGeneration.Generator;
using FireStarter.CodeGeneration.Parser;

namespace FireStarter.CodeGeneration
{
    public class TemplateUtilities
    {
        public static TemplateExpression GetTemplateFromFile(string templateFileName, out string errorMessage)
        {
            TemplateExpression templateExpression = null;
            errorMessage = null;
            string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            if (!templateFileName.Contains(currentDirectory))
            {
                templateFileName = Path.Combine(currentDirectory, templateFileName.Replace('/', Path.DirectorySeparatorChar));
            }
            if (!File.Exists(templateFileName))
            {
                errorMessage = String.Format("FAILED: A required template was not found: {0}", templateFileName);
                errorMessage = errorMessage.Replace('/', '\\');
            }
            else
            {
                StatementParser templateParser = new StatementParser();
                string template = File.ReadAllText(templateFileName);
                string templateCopy = template;
                templateExpression = templateParser.Parse(ref templateCopy);
            }
            return templateExpression;
        }
    }
}